package com.music.intercetor;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.music.entity.CmUser;
import com.music.utils.CookieCmUser;
import com.music.utils.RedisUtils;;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by 54110 on 2020/12/2.
 */
@Component
public class MyInterceptor implements HandlerInterceptor {

   @Resource
   RedisUtils redisUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        String number=null;
        for (Cookie cook:cookies
             ) {
            if (cook.getName().equals("token")){
                number=cook.getValue();
            }
        }
        Object o1 = redisUtils.get(number);
        String s = JSONObject.toJSONString(o1);
        CmUser cmUser = JSON.parseObject(s, CmUser.class);
        System.out.println(cmUser);
        if(cmUser!=null){
            return true;
        }
//        //使用session判断用户是否登录
//        HttpSession session = request.getSession();
//        Object attribute = session.getAttribute(name);
//        if (attribute!=null){
//            //从session获取用户的权限，在用户登录时，就已经将权限放置在session中判断用户权限
//            List<TbPremission> byUserName = (List) session.getAttribute(name + "_per");
//            //获取到前端发起的请求路径
//            //循环list 获取到权限名称放置到新的list中
//            List prelist = new ArrayList<>();
//            for (TbPremission per:byUserName
//                 ) {
//                prelist.add(per.getPermissionName());
//            }
//            String requestURI = request.getRequestURI();
//            if (prelist.contains(requestURI)){
//                return true;
//            }else{
//                response.setCharacterEncoding("utf-8");
//                response.setContentType("application/json");
//                PrintWriter writer = response.getWriter();
//                writer.print("不配，充钱！！，不允许访问");
//                return false;
//            }
//
//        }
//        response.setCharacterEncoding("utf-8");
//        response.setContentType("application/json");
//        PrintWriter writer = response.getWriter();
//        writer.print("您当前未登录，不允许访问");
//
//
        return false;
    }

}
